// import download from '../api/download'
// import config from '../config'
const app = getApp()
// 文件扩展名匹配正则
const getFileExtendingName = (url) => {
  const matches = url.match(/\.[^\.]+$/)
  if (matches) return matches[0]
  return ''
}

/**
 * 转义HTML标签的方法
 * @param  {String} str 需要转义的HTML字符串
 * @return {String}     转义后的字符串
 */
const funEncodeHTML = (str) => {
  if (typeof str === 'string') {
    return str.replace(/<|&|>/g, (matches) => {
      return ({
        '<': '&lt;',
        '>': '&gt;',
        '&': '&amp;'
      })[matches]
    })
  }
  return ''
}

/**
 * 反转义HTML标签的方法
 * @param  {String} str 需要反转义的字符串
 * @return {String}     反转义后的字符串
 */
const funDecodeHTML = (str) => {
  if (typeof str === 'string') {
    return str.replace(/&lt;|&gt;|&amp;/g, (matches) => {
      return ({
        '&lt;': '<',
        '&gt;': '>',
        '&amp;': '&'
      })[matches]
    })
  }
  return ''
}

// 格式化数字
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

// // 加载自定义字体
// const loadFontFace = (fonts = []) => {
//   fonts.forEach(v => {
//     wx.loadFontFace({
//       global: true,
//       family: v.family,
//       source: `url('${config.URL_PREFIX}/fonts/${v.file}')`,
//       // success: console.log,
//       fail: console.log
//     })
//   })
// }

/**
 * 二次封装openDocument
 * @param url 文件下载地址
 * @param fileName 指定文件名字（包含后缀，若是纯标题则需要解开下面注释）
 * @param showMenu 是否显示右上角菜单
 */
// const openDocument = (url, fileName, showMenu = true) => {
//   wx.showLoading({ title: '正在打开' })
//   // 添加后缀 如果fileName不包含后缀则需要解开下面注释
//   // fileName = fileName + getFileExtendingName(url)
//   download.downloadFile(url, fileName).then((filePath) => {
//     wx.openDocument({
//       filePath,
//       showMenu,
//       success: (res) => {
//         console.log('openDocument success', res)
//         wx.hideLoading()
//       },
//       fail: (err) => {
//         console.log('openDocument fail', err)
//         showToast('打开失败')
//         wx.hideLoading()
//       }
//     })
//   }).catch((error) => {
//     showToast('下载失败')
//     wx.hideLoading()
//   })
// }

/**
 * 二次封装navigateBack
 * @param delta 返回的页面数，如果 delta 大于现有页面数，则返回到首页
 */
const navigateBack = (delta = 1) => {
  wx.navigateBack({
    delta,
    fail: (err) => {
      console.log('navigateBack fail', err)
      wx.reLaunch({
        url: '/pages/index/index'
      })
    }
  })
}

/**
 * 二次封装openSetting
 * @param scope 用户授权设置信息属性（默认为scope.writePhotosAlbum）
 * @param withSubscriptions 是否同时获取用户订阅消息的订阅状态，默认不获取
 */
const openSetting = (scope = 'scope.writePhotosAlbum', withSubscriptions = false) => {
  return new Promise((resolve, reject) => {
    // const content = `您拒绝了“${constants.scopeMappings[scope]}”授权\n请点击确定按钮重新打开授权`
    showModal('提示', content).then((result) => {
      // console.log(result)
      wx.openSetting({
        withSubscriptions,
        success: (res) => {
          // console.log('openSetting success', res)
          if (res.authSetting[scope]) {
            resolve(res)
          } else {
            reject(res)
          }
        },
        fail: (err) => {
          console.log('openSetting fail', err)
          reject(err)
        }
      })
    }).catch((error) => {
      reject(error)
    })
  })
}

/**
 * 二次封装showModal
 * @param title 提示的标题
 * @param content 提示的内容
 * @param options 其它配置选项
 */
const showModal = (title = '', content = '', options = {}) => {
  return new Promise((resolve, reject) => {
    wx.showModal({
      ...options,
      content,
      title,
      success: (res) => {
        // console.log('showModal success', res)
        if (res.confirm) {
          resolve(res)
        } else {
          reject(res)
        }
      },
      fail: (err) => {
        console.log('showModal fail', err)
        reject(err)
      }
    })
  })
}

/**
 * 二次封装showToast
 * @param title 提示的内容
 * @param icon 图标
 * @param options 其它配置选项
 */
const showToast = (title = '系统异常，请稍后再试~', icon = 'none', options = {}) => {
  wx.showToast({ ...options, title, icon })
}

/**
 * object 转 query string
 * @param obj 需要转化的对象
 */
const queryStr = (obj = {}) => {
  return Object.keys(obj).map(v => `${encodeURIComponent(v)}=${encodeURIComponent(obj[v])}`).join('&')
}

// 防抖函数
const debounce = (fn, delay = 1000) => {
  let timer = null
  return function () {
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, arguments)
    }, delay)
  }
}

// 节流函数
const throttle = (fn, delay = 5000) => {
  let preTime = +new Date()
  return function () {
    const nowTime = +new Date()
    if (nowTime - preTime >= delay) {
      fn.apply(this, arguments)
      preTime = nowTime
    }
  }
}

// const formatTime = date => {
//   const year = date.getFullYear()
//   const month = date.getMonth() + 1
//   const day = date.getDate()
//   const hour = date.getHours()
//   const minute = date.getMinutes()
//   const second = date.getSeconds()

//   return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
// }
const formatTimeDay = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return `${[year, month, day].map(formatNumber).join('-')}`
}
const formatTimeminute = date => {
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()


  return `${[hour, minute].map(formatNumber).join('.')}`
}
  // JS获取url参数
function parameter(url, paramName) {
  const paramsObj = {};
  // 提取URL中?后面的查询参数部分（排除#哈希部分）
  const match = url.match(/\?([^#]*)/);
  
  if (match) {
    const queryString = match[1];
    // 分割各个参数对
    queryString.split('&').forEach(pair => {
      // 分割键值对
      let [key, value] = pair.split('=');
      // 解码参数名和值
      key = decodeURIComponent(key || '');
      value = value ? decodeURIComponent(value) : '';
      // 存储到对象（重复参数后者覆盖前者）
      paramsObj[key] = value;
    });
  }

  // 返回请求结果
  return typeof paramName !== 'undefined' ? paramsObj[paramName] : paramsObj;
}
  // JS获取url参数
function getParams(url, paramName) {
  const paramsObj = {};
  // 提取URL中?后面的查询参数部分（排除#哈希部分）
  const match = url.match(/\?([^#]*)/);
  
  if (match) {
    const queryString = match[1];
    // 分割各个参数对
    queryString.split('&').forEach(pair => {
      // 分割键值对
      let [key, value] = pair.split('=');
      // 解码参数名和值
      key = decodeURIComponent(key || '');
      value = value ? decodeURIComponent(value) : '';
      // 存储到对象（重复参数后者覆盖前者）
      paramsObj[key] = value;
    });
  }

  // 返回请求结果
  return typeof paramName !== 'undefined' ? paramsObj[paramName] : paramsObj;
}

//随机生成 min 到 max 之间的整数
function random(min,max){
    return Math.floor((max-min+1)*Math.random())+min;
}

// len:生成整数的数量   start:最小值   end:最大值
function getRandomArr(len,start,end){
    let arr=[];
    while (arr.length<len){
        let num=random(start,end);
        if(arr.indexOf(num)==-1){
            arr.push(num);
        }
    }
    return arr;
}
//微信小程序
function saveImg(url){
    wx.downloadFile({
        url,//图片地址
        success: function (res) {
          //图片保存到本地
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: function (data) {
              wx.hideLoading()
              wx.showModal({
                // title: '提示',
                content: '保存成功,请去相册查看',
                showCancel: false,
              })
            },
            fail: function (err) {
              if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
                // 这边微信做过调整，必须要在按钮中触发，因此需要在弹框回调中进行调用
                wx.showModal({
                  title: '提示',
                  content: '需要您授权保存相册',
                  showCancel: false,
                  success: modalSuccess => {
                    wx.openSetting({
                      success(settingdata) {
                        console.log("settingdata", settingdata)
                        if (settingdata.authSetting['scope.writePhotosAlbum']) {
                          wx.showModal({
                            title: '提示',
                            content: '获取权限成功,再次点击图片即可保存',
                            showCancel: false,
                          })
                        } else {
                          wx.showModal({
                            title: '提示',
                            content: '获取权限失败，将无法保存到相册哦~',
                            showCancel: false,
                          })
                        }
                      },
                      fail(failData) {
                        console.log("failData", failData)
                      },
                      complete(finishData) {
                        console.log("finishData", finishData)
                      }
                    })
                  }
                })
              }
            },
            complete(res) {
              wx.hideLoading()
            }
          })
        }
    })
}


function filterObjArr(objArr, str) {
  return objArr.map(obj => {
    const newObj = {};
    for (const key in obj) {
      if (key === str) {
        newObj[key] = obj[key];
      }
    }
    return newObj;
  }).filter(obj => Object.keys(obj).length > 0);
}

function filterImg(arr,str) {
  const result = arr.filter(obj => obj.hasOwnProperty(str));
  return result.map(obj => obj[str]);
}
//时间戳转换 10位需*1000
const formatDate = (time, format) => {
  // if(typeof(time) == 'string' ){
  if(typeof(time) == 'string' && time.indexOf('/') != -1){
    time = time.replace(/-/g, '/')
  }
  time = time.replace(/-/g,':').replace(' ',':');
  time = time.split(':');
  var date = new Date(Number(time[0]) ,Number((time[1]-1)),Number(time[2]),Number(time[3]),Number(time[4]),Number(time[5]));
  var y = date.getFullYear();
  var m = date.getMonth() + 1;
  m = m < 10 ? ('0' + m) : m;
  var d = date.getDate();
  d = d < 10 ? ('0' + d) : d;
  var h = date.getHours();
  h = h < 10 ? ('0' + h) : h;
  var minute = date.getMinutes();
  var second = date.getSeconds();
  minute = minute < 10 ? ('0' + minute) : minute;
  second = second < 10 ? ('0' + second) : second;
  if (format === 'yyyy-MM-dd')
    return y + '-' + m + '-' + d
  else if (format === 'yyyy.MM.dd')
    return y + '.' + m + '.' + d
  else if (format === 'HH:mm:ss')
    return h + ':' + minute + ':' + second;
  else if(format == 'mm.dd.hh:ss')
    return y + '年' + m + '月' + d + '日' + ' ' + h + ':' + minute;   //yyyy月MM日dd h:m
    // console.log(m,d,h,minute)
    // return  String(m)  + '月' + String(d) + '日' + ' ' + String(h) + ':' + String(minute)+'';   //yyyy月MM日dd h:m
    else if(format == 'mm.dd.hh.mm:ss')
    // console.log(m,d,h,minute)
    return  m + '月' + d + '日' + ' ' + h + ':' + minute+':'+second;   //yyyy月MM日dd h:m
  else
  return y + '年' + m + '月' + d + '日' + ' ' + h + ':' + minute;   //yyyy月MM日dd h:m
}

// 检查用户的游玩信息
function getPlaygame(data = {}) {
  return new Promise((resolve, reject) => {
      let params = data
      app.$http.post('/Comics/PlayGame', params, false, "json").then(res => {
          resolve(res)
          // if (res.code == 200 || res.code == 201) {
          //     resolve(res)
          // } else {
          //      // const error = new Error("数据获取失败");
          //      reject(res)
          // }
      })
  })
}


function formatTime(seconds) {
  var minutes = Math.floor(seconds / 60);
  var remainingSeconds = seconds % 60;
  return padTwoDigits(minutes) + ":" + padTwoDigits(remainingSeconds);
}

function padTwoDigits(number) {
  return number < 10 ? "0" + number : number.toString();
}




module.exports = {
  getFileExtendingName,
  funEncodeHTML,
  funDecodeHTML,
  formatNumber,
  // loadFontFace,
  // openDocument,
  navigateBack,
  openSetting,
  showModal,
  showToast,
  queryStr,
  debounce,
  throttle,
  // formatTime,
  formatTimeDay,
  formatTimeminute,
  getRandomArr,
  saveImg,
  filterObjArr,
  filterImg,
  formatDate,
  getParams,
  parameter,
  getPlaygame,


  formatTime,
}